import axios from 'axios';

import { agentConfig } from '$domain/model/agent/config';
import { logger, promiseRetry } from '$common';
import { SimJobStatus, JobResultNotification, SimProcess } from '../type';
class ReportService {

  private readonly maxRetryCount: number = 5;
  private gatewayUrl: string;

  constructor(private gatewayHost:string, private gatewayPort: number) {
    this.gatewayUrl = `http://${this.gatewayHost}:${this.gatewayPort}`;
  }

  async jobStatusReport(jobId: string, status: SimJobStatus) {
    const url = `${this.gatewayUrl}/api/jobs/${jobId}/status`;
    logger.debug(`🎈 ==> Notify gateteway to update job status jobId: ${jobId}`);
    return await this.postRetry(url, { status });
  }

  async jobResultReport(jobResult: JobResultNotification) {
    const url = `${this.gatewayUrl}/api/jobs/${jobResult.id}/result`;
    logger.debug(`🎈 ==> Notify gateteway job result, jobId: ${jobResult.id}`);
    return await this.postRetry(url, jobResult);
  }

  async jobProcessReport(jobId: string, process: SimProcess) {
    const url = `${this.gatewayUrl}/api/job/progress/${jobId}`;
    logger.debug(`🎈 ==> Notify gateteway job process info, jobId: ${jobId}`);
    return await axios.post(url, process);
  }

  private async postRetry(url: string, data: unknown) {
    logger.debug(`🎈 send http post to ${url}, data: ${JSON.stringify(data, null, 2)}`);
    await promiseRetry(async(retry, times) => {
      try {
        return await axios.post(url, data, { maxBodyLength: Infinity });
      } catch (ex) {
        logger.error(ex.message);
        logger.info(`retry ${times} times`);
        retry(ex);
      }
    }, this.maxRetryCount);
  }
}

export const reportService = new ReportService(agentConfig.gatewayHost, agentConfig.gatewayPort);